package com.shujia.day14;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo05LockAndUnlock {
    public static void main(String[] args) {
        TickLock tickLock = new TickLock(100, new ReentrantLock());
        new Thread(tickLock,"销售员1").start();
        new Thread(tickLock,"销售员2").start();

    }

    static class TickLock implements Runnable {
        int tickNum;
        Lock lock;

        public TickLock(int tickNum, Lock lock) {
            this.tickNum = tickNum;
            this.lock = lock;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                // TODO 相当于在当前位置添加了一个 synchronized 同步锁
                lock.lock();
                if (tickNum > 0) {
                    sell();
                } else {
                    break;
                }
                lock.unlock();
            }
        }

        public void sell() {
            System.out.println("当前售票员:" + Thread.currentThread().getName() + "正在销售第" + tickNum + "票");
            tickNum -= 1;
        }
    }
}
